﻿using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace BuddHa.Common.CryptoOpex.RSAUtil.Implementation
{
    public class RSAPkcs8Formatter : RSAFormatter
    {
        protected sealed override RSAParameters CreateByPublicKey(string key)
        {
            var publicKey = KeyFormatRemove(key, "PRIVATE KEY");
            var publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
            var rsaParameters = new RSAParameters();
            rsaParameters.Modulus = publicKeyParam.Modulus.ToByteArrayUnsigned();
            rsaParameters.Exponent = publicKeyParam.Exponent.ToByteArrayUnsigned();
            return rsaParameters;
        }

        protected sealed override RSAParameters CreateByPrivateKey(string key)
        {
            var privateKey = KeyFormatRemove(key, "PRIVATE KEY");
            var privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
            var rsaParameters = new RSAParameters();
            rsaParameters.Modulus = privateKeyParam.Modulus.ToByteArrayUnsigned();
            rsaParameters.Exponent = privateKeyParam.PublicExponent.ToByteArrayUnsigned();
            rsaParameters.P = privateKeyParam.P.ToByteArrayUnsigned();
            rsaParameters.Q = privateKeyParam.Q.ToByteArrayUnsigned();
            rsaParameters.DP = privateKeyParam.DP.ToByteArrayUnsigned();
            rsaParameters.DQ = privateKeyParam.DQ.ToByteArrayUnsigned();
            rsaParameters.InverseQ = privateKeyParam.QInv.ToByteArrayUnsigned();
            rsaParameters.D = privateKeyParam.Exponent.ToByteArrayUnsigned();

            return rsaParameters;
        }
    }
}
